<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<title>智能交互</title>
		{% load static %}
		<link href="{% static 'css/style.css' %}" rel="stylesheet">
		<link href="{% static 'plugins/bootstrap-5.3.0/css/bootstrap.min.css' %}" rel="stylesheet">
		<link href="{% static 'css/training.css' %}" rel="stylesheet">
<style>
.custom-file-upload {
margin: 5px 0;
border: 1px dashed #ccc;
border-radius: 4px;
padding: 3px;
background-color: white;
cursor: pointer;
transition: all 0.3s ease;
text-align: center;
}

.text-placeholder {
	height: 100px;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #f5f5f5;
	border-radius: 8px;
	margin: 20px 0;
}

.custom-file-upload:hover {
border-color: #007bff;
background-color: #f8f9fa;
}

.custom-file-upload i {
font-size: 24px;
margin-right: 1px;
}

.upload-container {
transition: all 0.3s ease;
}

.feedback-message {
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
z-index: 10000;
display: none;
align-items: center;
padding: 10px 20px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
animation: fadeInOut 4s ease-in-out forwards;
}

.feedback-message.success {
background-color: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}

.feedback-message.error {
background-color: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}

.feedback-icon {
margin-right: 8px;
}

@keyframes fadeInOut {
0% {
opacity: 0;
top: 0;
}
10% {
opacity: 1;
top: 20px;
}
90% {
opacity: 1;
top: 20px;
}
100% {
opacity: 0;
top: 0;
}
}

/* 确保文件详情区域始终显示 */
.file-details {
margin-top: 5px;
}

/* 文件名和大小样式 */
.file-info-label {
font-weight: bold;
color: #666;
}

.file-info-value {
font-weight: bold;
color: #333;
}

/* 添加结果列表样式 */
.results-container {
margin-top: 20px;
padding: 20px;
max-height: 400px; /* 限制高度，超出后自动出现滚动条 */
overflow-y: auto; /* 垂直方向滚动 */
border-radius: 10px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

/* 历史记录表格强制对齐 */
.results-table {
width: 97%;
table-layout: fixed;
border-collapse: collapse;
background-color: white;
border-radius: 10px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
overflow: hidden;
margin-left: 10%;
}

.results-table th,
.results-table td {
padding: 12px 15px;
border-bottom: 1px solid #dee2e6;
word-wrap: break-word;
text-align: center;
vertical-align: middle;
}

.results-table th:nth-child(1),
.results-table td:nth-child(1) {
width: 11%; /* 编号 */
}

.results-table th:nth-child(2),
.results-table td:nth-child(2) {
width: 40%; /* 视频文件名 */
text-align: left;
}

.results-table th:nth-child(3),
.results-table td:nth-child(3) {
width: 15%; /* 文件大小 */
}

.results-table th:nth-child(4),
.results-table td:nth-child(4) {
width: 15%; /* 情感类型 */
}

.results-table th:nth-child(5),
.results-table td:nth-child(5) {
width: 12%; /* 分析帧数 */
}

.module-header {
background-color: #337ab7;
color: white;
padding: 12px 15px;
margin: 0; /* 清除 margin */
border-radius: 10px 10px 0 0;
text-align: center;
font-weight: bold;
width: 100%; /* 宽度100% */
box-sizing: border-box; /* 确保 padding 不影响宽度 */
}

/* 调整模块的 padding，避免标题覆盖内容 */
.module {
padding: 0; /* 清除模块的内边距 */
padding-top: 20px; /* 只保留上内边距，给标题留空间 */
width: 26%;
background-color: #f9f9f9;
border-radius: 10px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
text-align: center;
}
.module-container {
display: flex;
justify-content: center;
position: relative; /* 保持relative定位 */
top: 0;
left: 0;
transform: none;
width: 100%;
max-width: 1400px;
gap: 5%;
margin: 10px auto;
padding-top: 0; /* 确保无额外上内边距 */
}
.current-result-content p {
margin: 15px 0;
text-align: left;
padding-left: 20%;
}

.emotion-result {
font-size: 18px;
font-weight: bold;
}

.emotion-positive {
color: #28a745;
}

.emotion-negative {
color: #dc3545;
}

.emotion-neutral {
color: #ffc107;
}

.progress-container {
margin-top: 15px;
display: none;
}

.progress {
height: 20px;
margin-bottom: 10px;
border-radius: 10px;
background-color: #f5f5f5;
box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1);
}

.progress-bar {
height: 100%;
border-radius: 10px;
background-color: #337ab7;
width: 0%;
transition: width 0.3s ease;
text-align: center;
line-height: 20px;
color: white;
}

.progress-text {
font-size: 12px;
color: #666;
text-align: center;
}

.upload-btn {
background-color: #337ab7;
color: white;
border: none;
padding: 8px 16px;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s ease;
min-width: 100px;
}

.upload-btn:hover {
background-color: #286090;
}

.upload-btn:disabled {
background-color: #cccccc;
cursor: not-allowed;
}

.upload-btn.uploading {
background-color: #f0ad4e;
}

.function_link {
text-decoration: none;
color: inherit;
font-size: 18px;
margin-left: 8px;
}

/* 新增样例视频模块样式 */
/*.sample-videos-container {*/
/*    width: 90%;*/
/*    max-width: 1400px;*/
/*    margin: 250px auto 30px;*/
/*    padding: 20px;*/
/*    background-color: #f9f9f9;*/
/*    border-radius: 10px;*/
/*    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);*/
/*    text-align: center;*/
/*}*/
.sample-videos-container {
width: 90%;
max-width: 1400px;
margin: 40px auto 30px;  /* 减少上边距，因为模块容器不再是绝对定位 */
padding: 20px;
background-color: #f9f9f9;
border-radius: 10px;
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
text-align: center;
}

.sample-videos-header {
background-color: #337ab7;
color: white;
padding: 10px 15px;
margin: -20px -20px 20px -20px;
border-radius: 10px 10px 0 0;
text-align: center;
font-weight: bold;
}

.sample-videos-grid {
display: flex;
justify-content: space-around;
flex-wrap: wrap;
gap: 20px;
margin-top: 20px;
}

.sample-video-item {
width: 30%;
min-width: 250px;
background-color: white;
border-radius: 8px;
padding: 15px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}

.sample-video-item:hover {
transform: translateY(-5px);
}

.sample-video-wrapper {
position: relative;
padding-bottom: 56.25%; /* 16:9 比例 */
height: 0;
overflow: hidden;
margin-bottom: 10px;
border-radius: 5px;
background-color: #000;
}

.sample-video-wrapper video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
cursor: pointer;
}

.sample-video-info {
text-align: left;
margin-top: 10px;
}

.sample-video-info p {
margin: 5px 0;
font-size: 14px;
}

.video-info-label {
font-weight: bold;
color: #666;
}

.video-info-value {
font-weight: bold;
color: #333;
}
/* 若只想让主内容区域滚动（可选），可保留下面这段 */
.main_content {
overflow-y: auto;
min-height: 90vh;     /* 保证至少一屏高 */
}

.home-link {
  text-decoration: none; /* 去除下划线 */
  color: white; /* 继承按钮文字颜色 */
  display: inline-block; /* 确保点击区域与按钮一致 */
}

/* 按钮样式调整 */
.home-btn {
  padding: 15px !important; /* 确保内边距生效 */
  font-size: 25px !important; /* 确保字体大小生效 */
  background-color: #156bb7;
  border-radius: 4px; /* 统一圆角 */
  transition: all 0.2s ease; /* 平滑过渡效果 */
  border: none; /* 去除边框 */
  cursor: pointer; /* 鼠标指针样式 */
}

/* 悬停效果 */
.home-btn:hover {
  opacity: 0.9; /* 轻微透明效果 */
  transform: translateY(-2px); /* 轻微上浮 */
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3); /* 增强阴影 */
}

/* 点击效果 */
.home-btn:active {
  transform: translateY(0); /* 恢复位置 */
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2); /* 减弱阴影 */
}

/* 确保按钮在各种状态下样式一致 */
.home-link:visited .home-btn {
  color: #fff; /* 访问后保持白色文字 */
}
</style>
	</head>
	<body>
		<!-- 导航栏（Bootstrap 5 写法） -->
		<nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
			<div class="container-fluid">
				<a class="navbar-brand d-flex align-items-center" href="#">
					<!-- <img src="{% static 'images/logo.png' %}" alt="Logo" class="nav-logo me-2"> -->
					<div class="nav-title">情感分析与智能引导</div>
				</a>

				<div class="user-actions">
				<!-- <el-button type="primary" class="login-btn">登录</el-button> -->
				<a href="http://10.68.100.169:25001" class="home-link">
					<el-button type="primary" class="register-btn home-btn" style="padding: 25px;font-size: 25px;">回到首页</el-button>
				</a>
				</div>
			</div>
		</nav>

		<!-- 侧边栏（保持不变） -->
		<div class="sidebar-container">
			<div class="sidebar" style="margin-top: 45px;">
				<h2 class="sidebar-title">功能模块</h2>
				<ul class="nav-list">
					<li class="nav-item" style="margin-left:20px;">
						<a href="/emotion/upload" class="active function_link" style="font-size: 25px;">情感分析</a>
					</li>
					<li class="nav-item" style="margin-left:20px;">
						<a href="/intelligence/interaction" class="active function_link" style="font-size: 25px;">文本引导</a>
					</li>
                    <li class="nav-item" style="margin-left:20px;">
                        <a href="/intelligence/image_generator" class="active function_link" style="font-size: 25px;">图片引导</a>
                    </li>
				</ul>
			</div>
		</div>

		<!-- 主内容 -->
		<div class="main_content">
				<div class="row" style="margin-top: 35px; margin-left: 200px;">
					<!-- 左侧 输入模块 -->
					<div class="col-md-6 offset-md-1">
						<div class="card">
							<div class="card-header" style="background: linear-gradient(to right, #337ab7, #43a047); color: #fff;">
								<h4 class="card-title">交互输入</h4>
							</div>
							<div class="card-body">
								<form id="sendForm">
									<div class="mb-3">
										<label for="event" class="form-label">输入事件主题</label>
										<textarea class="form-control" id="event" rows="3" placeholder="示例：新能源汽车发生火灾"
											style="resize: none;">AI普及引发部分岗位被替代</textarea>
									</div>
									<div class="mb-3">
										<label for="guideline" class="form-label">输入引导方向</label>
										<textarea class="form-control" id="guideline" rows="3"
											placeholder="示例：引导用户理性看待新能源技术发展的阶段性问题" style="resize: none;">引导用户关注人机协同与新技能培养</textarea>
									</div>
									<div class="mb-3">
										<label for="misconception" class="form-label">输入用户观点</label>
										<textarea class="form-control" id="misconception" rows="3"
											placeholder="示例：新能源车根本不安全，应该全面禁用" style="resize: none;">AI迟早让所有人失业，我们根本不该发展它</textarea>
									</div>
								</form>
								<button type="button" class="btn btn-primary col-md-2 offset-md-10 " id="sendButton" disabled style="margin-top: 20px;">
									<span class="spinner-border spinner-border-sm me-2 d-none" id="loadingSpinner"></span>
									<span id="btnText">发送</span>
								</button>
							</div>
						</div>
						<br>
						<div class="card" style="height: 200px;" id="resultPanel">
							<div class="card-header">
									<h4 class="card-title">输出的引导文本</h4>
							</div>
							<div class="card-body" id="resultPanelBody">
                                <p class="text-placeholder" style="color: #999;">生成的引导文本将显示在这里</p>
							</div>
							<!-- <div class="card-body" id="resultPanelBody" >
							</div> -->
						</div>
					</div>


					<!-- 右侧 模型信息+按钮 -->
					<div class="col-md-3 offset-md-1">
						<div class="card">
							<div class="card-header">
								<h4 class="card-title">模型信息</h4>
							</div>
							<div class="card-body">
								<p><strong>模型名称：</strong> 智能交互模型V1.0</p>
								<p><strong>响应时间：</strong> <span id="responseTime">-- ms</span></p>
							</div>
						</div>
						<br>
						<div class="card sample-card">
							<div class="card-body text-center">
								<h5 style="text-align: left;"><strong>样例主题：新能源汽车引发火灾</strong></h5>
								<h6 style="text-align: left;">引导方向：引导用户理解火灾可能涉及多个因素</h6>
								<h6 style="text-align: left;">用户观点：新能源车根本不安全，应该全面禁用</h6>
								<button class="btn btn-primary" onclick="fillExample(1)">点击使用样例</button>
							</div>
						</div>
						<br>
						<div class="card sample-card">
							<div class="card-body text-center">
								<h5 style="text-align: left;"><strong>样例主题：某网红直播带货虚假宣传引发舆论</strong></h5>
								<h6 style="text-align: left;">引导方向：引导用户理性区分个别主播与整个行业</h6>
								<h6 style="text-align: left;">用户观点：直播带货都是骗人的，应该全部取缔！</h6>
								<button class="btn btn-primary" onclick="fillExample(2)">点击使用样例</button>
							</div>
						</div>
						<br>
						<div class="card sample-card">
							<div class="card-body text-center">
								<h5 style="text-align: left;"><strong>样例主题：AI普及引发部分岗位被替代</strong></h5>
								<h6 style="text-align: left;">引导方向：引导用户关注人机协同与新技能培养</h6>
								<h6 style="text-align: left;">用户观点：AI迟早让所有人失业，我们根本不该发展它</h6>
								<button class="btn btn-primary" onclick="fillExample(3)">点击使用样例</button>
							</div>
						</div>


					</div>
				</div>

				<!-- 输出结果 -->
				<div class="results-container" style="margin-left: 100px;">
					<h4 style="margin-bottom: 20px; color: #333;">历史记录</h4>
					<table class="table table-striped table-bordered">
						<thead>
							<tr>
								<th>时间</th>
								<th>事件</th>
								<th>引导方向</th>
								<th>输入文本</th>
								<th>输出文本</th>
							</tr>
						</thead>
						<tbody id="resultsTableBody">
							<!-- 结果将通过JavaScript动态添加 -->
						</tbody>
					</table>
				</div>
			</div>
		</div>

		<!-- 引入Bootstrap JavaScript -->
		<script src="{% static 'js/jquery.js' %}"></script>
		<script src="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.min.js' %}"></script>
		<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
		<script>
			//样例池
			const examples = {
			1: {
				event: "新能源汽车引发火灾",
				guideline: "引导用户理解火灾可能涉及多个因素，不应武断否定新能源车的发展",
				misconception: "新能源汽车经常自燃，说明这项技术根本不成熟，应该全部禁售"
			},
			2: {
				event: "某网红直播带货虚假宣传引发舆论",
				guideline: "引导用户理性区分个别主播与整个行业",
				misconception: "直播带货都是骗人的，应该全部取缔！"
			},
			3: {
				event: "AI普及引发部分岗位被替代",
				guideline: "引导用户关注人机协同与新技能培养",
				misconception: "AI迟早让所有人失业，我们根本不该发展它"
			}
			};

			// 一键填充函数
			function fillExample(no) {
			const data = examples[no];
			document.getElementById("event").value         = data.event;
			document.getElementById("guideline").value     = data.guideline;
			document.getElementById("misconception").value = data.misconception;

			// 触发输入事件，让“发送”按钮状态自动刷新
			["event", "guideline", "misconception"].forEach(id => {
				document.getElementById(id).dispatchEvent(new Event("input"));
			});
			}

			document.addEventListener("DOMContentLoaded", () => {
				const event = document.getElementById("event");
				const guideline = document.getElementById("guideline");
				const misconception = document.getElementById("misconception");
				const sendButton = document.getElementById("sendButton");
				const refreshButton = document.getElementById("refreshButton");
				const responseTimeElement = document.getElementById("responseTime");
				const resultsTableBody = document.getElementById("resultsTableBody");
				const resultPanel = document.getElementById("resultPanel");
				const resultPanelBody = document.getElementById("resultPanelBody");

				// 更新按钮启用状态
				function updateSendButtonState() {
					const hasContent =
						event.value.trim() !== "" ||
						guideline.value.trim() !== "" ||
						misconception.value.trim() !== "";
					sendButton.disabled = !hasContent;
				}
				[event, guideline, misconception].forEach((el) =>
					el.addEventListener("input", updateSendButtonState)
				);

				// 从JSON文件加载历史记录
				async function loadHistory() {
					try {
						const response = await axios.get("{% url 'get_results_from_json' %}");
						if (response.status == 200) {
							const historyData = response.data.results || [];

							// 先清空表格，防止重复显示
							const resultsTableBody = document.getElementById("resultsTableBody");
							resultsTableBody.innerHTML = '';

							// 调用渲染函数
							renderHistory(historyData);
						} else {
							console.error("后端返回失败信息:", response.data.error);
						}
					} catch (error) {
						console.error("加载历史记录失败:", error);
					}
				}

				// 渲染历史记录到表格
				function renderHistory(historyList) {
					const resultsTableBody = document.getElementById("resultsTableBody");
					historyList.forEach(item => {
						const tr = document.createElement("tr");

						const tdTime = document.createElement("td");
						tdTime.textContent = item.timestamp || '-';
						tr.appendChild(tdTime);

						const tdEvent = document.createElement("td");
						tdEvent.textContent = item.request?.event || '-';
						tr.appendChild(tdEvent);

						const tdGuideline = document.createElement("td");
						tdGuideline.textContent = item.request?.guideline || '-';
						tr.appendChild(tdGuideline);

						const tdInput = document.createElement("td");
						tdInput.textContent = item.request?.misconception || '-';
						tr.appendChild(tdInput);

						const tdOutput = document.createElement("td");
						if (item.api_response?.status_code === 200 && item.api_response?.output) {
							tdOutput.textContent = item.api_response.output;
							tdOutput.classList.add("result-success");
						} else {
							tdOutput.textContent = item.api_response?.details || '无输出';
							tdOutput.classList.add("result-failure");
						}
						tr.appendChild(tdOutput);

						resultsTableBody.appendChild(tr);
					});
				}



				// 显示最近交互结果
				function showRecentResult(result) {
					// 清空之前的内容
					resultPanelBody.innerHTML = "";

					// 创建结果项容器
					const resultItem = document.createElement("div");
					resultItem.className = "result-item";

					// // 添加时间信息
					// const timeElement = document.createElement("div");
					// timeElement.innerHTML = `<span class="result-label">时间:</span>
		            //     <span class="result-value">${new Date().toLocaleString()}</span>`;
					// resultItem.appendChild(timeElement);

					// // 添加事件主题
					// const eventElement = document.createElement("div");
					// eventElement.innerHTML = `<span class="result-label">事件:</span>
		            //     <span class="result-value">${result.event || "-"}</span>`;
					// resultItem.appendChild(eventElement);

					// // 添加引导方向
					// const guidelineElement = document.createElement("div");
					// guidelineElement.innerHTML = `<span class="result-label">引导方向:</span>
		            //     <span class="result-value">${result.guideline || "-"}</span>`;
					// resultItem.appendChild(guidelineElement);

					// // 添加输入文本
					// const inputElement = document.createElement("div");
					// inputElement.innerHTML = `<span class="result-label">输入文本:</span>
		            //     <span class="result-value">${result.misconception || "-"}</span>`;
					// resultItem.appendChild(inputElement);

					// 添加输出结果
					const outputElement = document.createElement("div");
					// outputElement.innerHTML = `<span class="result-label">输出结果:</span>`;

					const outputValue = document.createElement("span");
					if (result.success) {
						outputValue.className = "result-value success";
						outputValue.textContent = result.guidance_text || "（无内容）";
					} else {
						outputValue.className = "result-value error";
						outputValue.textContent = result.error || "未知错误";
						if (result.details) {
							const details = document.createElement("div");
							details.className = "result-details";
							details.textContent = `详情: ${result.details}`;
							outputElement.appendChild(details);
						}
					}
					outputElement.appendChild(outputValue);
					resultItem.appendChild(outputElement);

					// // 添加响应时间
					// if (result.response_time) {
					// 	const timeElement = document.createElement("div");
					// 	timeElement.innerHTML = `<span class="result-label">响应时间:</span>
		            //         <span class="result-value">${result.response_time} ms</span>`;
					// 	resultItem.appendChild(timeElement);
					// }

					// 将结果项添加到面板
					resultPanelBody.appendChild(resultItem);

					// 显示面板
					resultPanel.style.display = "block";
				}

				sendButton.addEventListener("click", async () => {
					const title = event.value.trim() || "-";
					const direction = guideline.value.trim() || "-";
					const text = misconception.value.trim();
					const spinner = document.getElementById('loadingSpinner');
					const btnText = document.getElementById('btnText');

					resultPanelBody.innerHTML = "<div class=\"card-body\" id=\"resultPanelBody\"><p class=\"text-placeholder\" style=\"color: #999;\">生成的引导文本将显示在这里</p></div>";

					if (!text) {
						alert("请输入用户观点！");
						return;
					}

					// 记录开始时间
					const sendTime = Date.now();

					// 清空输入框并禁用按钮
					event.value = "";
					guideline.value = "";
					misconception.value = "";
					sendButton.disabled = true;
					spinner.classList.remove('d-none');
    				btnText.textContent= "生成中...";

					//发送数据
					const formData = new FormData();
					formData.append("event", title);
					formData.append("guideline", direction);
					formData.append("misconception", text);

					try {
						const response = await axios.post("{% url 'generate_guidance' %}", formData, {
							headers: {
								"X-CSRFToken": "{{ csrf_token }}",
								"Content-Type": "multipart/form-data"
							}
						});

						const result = response.data;
						const responseTime = result.response_time || (Date.now() - sendTime);
						responseTimeElement.textContent = `${responseTime} ms`;

						// 显示最近交互结果
						showRecentResult({
							event: title,
							guideline: direction,
							misconception: text,
							success: result.success,
							guidance_text: result.guidance_text,
							error: result.error,
							details: result.details,
							response_time: responseTime
						});

						// 构建新行
						const tr = document.createElement("tr");

						//时间
						const tdTime = document.createElement("td");
						tdTime.textContent = new Date().toLocaleString();
						tr.appendChild(tdTime);

						//事件
						const tdEvent = document.createElement("td");
						tdEvent.textContent = title;
						tr.appendChild(tdEvent);

						//方向
						const tdGuideline = document.createElement("td");
						tdGuideline.textContent = direction;
						tr.appendChild(tdGuideline);

						//输入内容
						const tdInput = document.createElement("td");
						tdInput.textContent = text;
						tr.appendChild(tdInput);

						//输出内容
						const tdOutput = document.createElement("td");
						tdOutput.id = "output";

						if (result.success) {
							tdOutput.classList.add("result-success");
							tdOutput.textContent = result.guidance_text || "（无内容）";
						} else {
							tdOutput.classList.add("result-failure");
							tdOutput.textContent =
								`模型错误：${result.error || '未知错误'}\n详情：${result.details || '无详细信息'}`;
						}

						tr.appendChild(tdOutput);
						resultsTableBody.appendChild(tr);
						tr.scrollIntoView({
							behavior: "smooth",
							block: "end"
						});

						// 发送后自动刷新历史记录
						loadHistory();
					} catch (error) {
						console.error("请求失败:", error);

						// 显示错误结果
						showRecentResult({
							event: title,
							guideline: direction,
							misconception: text,
							success: false,
							error: `服务器异常: ${error.message}`,
							response_time: Date.now() - sendTime
						});

						// 构建错误行
						const tr = document.createElement("tr");

						const tdTime = document.createElement("td");
						tdTime.textContent = new Date().toLocaleString();
						tr.appendChild(tdTime);

						const tdEvent = document.createElement("td");
						tdEvent.textContent = title;
						tr.appendChild(tdEvent);

						const tdGuideline = document.createElement("td");
						tdGuideline.textContent = direction;
						tr.appendChild(tdGuideline);

						const tdInput = document.createElement("td");
						tdInput.textContent = text;
						tr.appendChild(tdInput);

						const tdOutput = document.createElement("td");
						tdOutput.id = "output";
						tdOutput.classList.add("result-failure");
						tdOutput.textContent = `服务器异常：${error.message}`;
						tr.appendChild(tdOutput);

						resultsTableBody.appendChild(tr);
					}
					
					spinner.classList.add('d-none');
					btnText.textContent = "发送";

					event.focus(); // 聚焦回输入框
				});

				// 绑定发送与enter键
				document.addEventListener('keydown', function (e) {
				// 如果按的是 Enter 且发送按钮不是禁用状态，就触发点击
				if (e.key === 'Enter' && !document.getElementById('sendButton').disabled) {
					e.preventDefault();          // 阻止默认行为（如换行）
					document.getElementById('sendButton').click();
				}
				});

				// 初始化
				updateSendButtonState(); // 页面加载时初始化按钮状态
				loadHistory(); // 加载历史记录
			});
		</script>
	</body>
</html>